<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>我的订单 - 网上跳蚤市场</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
  <section class="fade-in">
    <h2>我的订单</h2>
    <div class="card">
      <div id="orderList"></div>
    </div>
    <div id="pagination" class="pagination mt-20"></div>

    <div class="mt-20">
      <div id="contactModal" class="modal">
        <div class="modal-content">
          <span class="close" id="closeContactModal">&times;</span>
          <h3 style="margin-top: 5px; margin-bottom: 15px; text-align: center; padding-top: 10px;">买家联系方式</h3>
          <div class="card">
            <p id="buyerUsername"></p>
            <p id="buyerPhone"></p>
          </div>
          <div style="text-align: center; margin-top: 15px;">
            <button id="closeContactBtn" class="btn" onclick="hideContactModal()">关闭</button>
          </div>
        </div>
      </div>
    </div>

    <div id="msg" class="mt-20"></div>
  </section>
</div>
<script>
  let page = 0, size = 10;

  async function loadSellerOrders() {
    try {
      document.getElementById('msg').innerHTML = '<div class="info-msg">正在加载订单数据...</div>';

      const res = await fetch(`/api/orders/seller?page=${page}&size=${size}`, {
        credentials: 'include'
      });

      // 检查是否需要登录
      if (res.status === 403 || res.status === 401) {
        window.location.href = '/login';
        return;
      }

      const data = await res.json();

      if (!data.content || data.content.length === 0) {
        document.getElementById('orderList').innerHTML = '<p class="text-center">暂无订单</p>';
        document.getElementById('pagination').innerHTML = '';
        document.getElementById('msg').innerHTML = '';
        return;
      }

      // 列表视图
      let html = '<table><tr><th>订单号</th><th>商品名称</th><th>数量</th><th>价格</th><th>买家</th><th>状态</th><th>下单时间</th><th>操作</th></tr>';

      for (const order of data.content) {
        // 格式化状态显示
        const statusMap = {
          'pending': '待处理',
          'accepted': '已接单',
          'shipped': '待收货',
          'completed': '已完成',
          'cancelled': '已取消',
          'reviewed': '已评价'
        };

        const statusClass = {
          'pending': 'status-pending',
          'accepted': 'status-shipped',
          'shipped': 'status-shipped',
          'completed': 'status-completed',
          'cancelled': 'status-cancelled',
          'reviewed': 'status-reviewed'
        };

        const status = statusMap[order.status] || order.status;
        const statusClassName = statusClass[order.status] || '';

        // 格式化日期
        const createdDate = new Date(order.createdAt).toLocaleString();

        // 商品和买家信息
        const productName = order.product ? order.product.name : '未知商品';
        const buyerName = order.buyer ? order.buyer.username : '未知用户';

        // 操作按钮
        let actionButtons = '';

        if (order.status === 'pending') {
          actionButtons = `
                    <button onclick="acceptOrder(${order.id})" class="btn success">接单发货</button>
                    <button onclick="cancelOrder(${order.id})" class="btn warning">取消订单</button>
                `;
        } else if (order.status === 'cancelled' || order.status === 'completed' || order.status === 'reviewed') {
          actionButtons = `<button onclick="confirmDelete(${order.id})" class="btn error">删除</button>`;
        }

        // 所有状态都可以联系买家
        actionButtons += `<button onclick="contactBuyer(${order.id})" class="btn contact-btn">联系买家</button>`;

        html += `<tr>
                <td>${order.id}</td>
                <td>${productName}</td>
                <td>${order.quantity}</td>
                <td>¥${order.totalPrice}</td>
                <td>${buyerName}</td>
                <td><span class="status-tag ${statusClassName}">${status}</span></td>
                <td>${createdDate}</td>
                <td class="flex">${actionButtons}</td>
            </tr>`;
      }

      html += '</table>';
      document.getElementById('orderList').innerHTML = html;

      // 分页
      let paginationHtml = '';
      for (let i = 0; i < data.totalPages; i++) {
        paginationHtml += `<button onclick="page=${i};loadSellerOrders()" class="${i === data.number ? 'active' : ''}">${i+1}</button>`;
      }
      document.getElementById('pagination').innerHTML = paginationHtml;
      document.getElementById('msg').innerHTML = '';

    } catch (e) {
      console.error('加载订单失败:', e);
      document.getElementById('orderList').innerHTML = '<p class="error-msg">加载订单失败，请刷新页面重试</p>';
      document.getElementById('msg').innerHTML = '';
    }
  }

  async function acceptOrder(orderId) {
    try {
      document.getElementById('msg').innerHTML = '<div class="info-msg">正在接单并发货...</div>';

      const res = await fetch(`/api/orders/${orderId}/status?status=shipped`, {
        method: 'POST',
        credentials: 'include'
      });

      const data = await res.json();

      if (data.error) {
        document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error}</div>`;
      } else {
        document.getElementById('msg').innerHTML = '<div class="success-msg">已接单并发货</div>';
        // 重新加载订单列表
        loadSellerOrders();
      }
    } catch (e) {
      console.error('操作失败:', e);
      document.getElementById('msg').innerHTML = '<div class="error-msg">操作失败，请重试</div>';
    }
  }

  async function cancelOrder(orderId) {
    if (confirm('确定要取消此订单吗？')) {
      try {
        document.getElementById('msg').innerHTML = '<div class="info-msg">正在取消订单...</div>';

        const res = await fetch(`/api/orders/${orderId}/status?status=cancelled`, {
          method: 'POST',
          credentials: 'include'
        });

        const data = await res.json();

        if (data.error) {
          document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error}</div>`;
        } else {
          document.getElementById('msg').innerHTML = '<div class="success-msg">订单已取消</div>';
          // 重新加载订单列表
          loadSellerOrders();
        }
      } catch (e) {
        console.error('操作失败:', e);
        document.getElementById('msg').innerHTML = '<div class="error-msg">操作失败，请重试</div>';
      }
    }
  }

  function showContactModal() {
    document.getElementById('contactModal').classList.remove('hidden');
    document.getElementById('contactModal').style.display = 'block';
  }

  function hideContactModal() {
    document.getElementById('contactModal').style.display = 'none';
  }

  async function contactBuyer(orderId) {
    try {
      console.log(`获取订单信息: ${orderId}`);
      document.getElementById('msg').innerHTML = '<div class="info-msg">正在获取买家联系方式...</div>';

      const res = await fetch(`/api/orders/${orderId}`, {
        credentials: 'include'
      });

      console.log('API响应状态:', res.status);

      if (res.ok) {
        const order = await res.json();
        console.log('订单数据:', order);

        if (order && order.buyer) {
          const buyer = order.buyer;
          console.log('买家信息:', buyer);

          document.getElementById('buyerUsername').innerHTML = `<strong>用户名:</strong> ${buyer.username || '未知用户'}`;
          document.getElementById('buyerPhone').innerHTML = `<strong>电话号码:</strong> ${buyer.phoneNumber || '未提供'}`;
          showContactModal();
          document.getElementById('msg').innerHTML = '';
        } else {
          console.error('买家信息不完整:', order);
          document.getElementById('msg').innerHTML = '<div class="error-msg">无法获取买家信息，数据不完整</div>';
        }
      } else {
        console.error('获取订单失败:', res.status);
        document.getElementById('msg').innerHTML = '<div class="error-msg">获取订单信息失败</div>';
      }
    } catch (e) {
      console.error('获取买家联系方式失败:', e);
      document.getElementById('msg').innerHTML = '<div class="error-msg">获取买家联系方式失败</div>';
    }
  }

  function confirmDelete(orderId) {
    if (confirm('确定要删除此订单记录吗？')) {
      deleteOrder(orderId);
    }
  }

  async function deleteOrder(orderId) {
    try {
      document.getElementById('msg').innerHTML = '<div class="info-msg">正在删除订单...</div>';

      const res = await fetch(`/api/orders/${orderId}`, {
        method: 'DELETE',
        credentials: 'include'
      });

      const data = await res.json();

      if (data.success) {
        document.getElementById('msg').innerHTML = '<div class="success-msg">订单已删除</div>';
        loadSellerOrders(); // 重新加载订单列表
      } else {
        document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '删除失败，请重试'}</div>`;
      }
    } catch (e) {
      console.error('删除订单失败:', e);
      document.getElementById('msg').innerHTML = '<div class="error-msg">删除失败，请重试</div>';
    }
  }

  // 设置模态框关闭按钮事件
  document.getElementById('closeContactModal').addEventListener('click', hideContactModal);

  // 页面加载时加载订单
  loadSellerOrders();

  // 确保DOM加载完成后添加事件监听
  document.addEventListener('DOMContentLoaded', function() {
    // 重新绑定关闭按钮事件，确保事件监听器正确添加
    document.getElementById('closeContactModal').addEventListener('click', hideContactModal);
    if (document.getElementById('closeContactBtn')) {
      document.getElementById('closeContactBtn').addEventListener('click', hideContactModal);
    }
  });
</script>
</body>
</html>